import { ref, reactive, onMounted, watch, onWatcherCleanup } from 'vue'
import type { CustomTableProps } from './customTable'
import { isArray, isDef, isObject } from '@/utils'
import axios from 'axios'

type Data = CustomTableProps['data']
type Page = {
  total: number
  currentPage: number
  pageSize: number
}

export const useRequestData = (
  lazy: CustomTableProps['lazy'],
  data: Data,
  loadConfig: CustomTableProps['loadConfig'],
  pagerConfig: CustomTableProps['pagerConfig'],
) => {
  const { pageSize } = pagerConfig
  const loading = ref(false)
  const tableData = ref<Data>(data || [])
  const page = reactive<Page>({
    total: 0,
    currentPage: 1,
    pageSize,
  })

  const getData = (controller?: AbortController) => {
    // 如果动态加载数据
    if (lazy && isObject(loadConfig)) {
      const { formatRes, url, method, ...restConfig } = loadConfig
      const { param: paramConf = {}, data: dataConf = {} } = restConfig as any
      if (isDef(url) && isDef(method)) {
        loading.value = true
        const pageConfig = {
          currentPage: page.currentPage,
          pageSize: page.pageSize,
        }
        axios({
          method,
          url,
          ...restConfig,
          // data: isDef(dataConf) ? { ...pageConfig, ...dataConf } : null,
          // params: isDef(paramConf) ? { ...pageConfig, ...paramConf } : null,
          signal: isDef(controller) ? controller.signal : undefined,
        })
          .then((res: unknown) => {
            if (formatRes) {
              res = formatRes(res)
            }
            if (isArray(res)) {
              tableData.value = res
              page.total = res.length
            }
          })
          .finally(() => {
            loading.value = false
          })
        return
      }
    }
    // 如果静态加载数据，则前端手动分页
    if (isArray(data)) {
      const { pageSize, currentPage } = page
      page.total = data.length
      tableData.value = data.slice((currentPage - 1) * pageSize, currentPage * pageSize)
    }
  }

  onMounted(() => {
    getData()
  })

  watch(page, () => {
    const controller: AbortController = new AbortController()
    getData(controller)
    onWatcherCleanup(() => {
      // 终止过期请求
      controller.abort()
    })
  })

  return {
    loading,
    tableData,
    page,
  }
}
